package com.heima.kafka.simple;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

/**
 * 生产者
 */
public class ProducerStart {

    public static void main(String[] args) {
        Properties properties = new Properties();
        // kafka 链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"114.116.122.120:9092");

        properties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG,60000);
        properties.put(ProducerConfig.RETRIES_CONFIG, 3);
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 1);
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 5);

        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        // 定义生产者
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);
        /**
         * 3.发送消息内容
         * ProducerRecord(String topic, K key, V value)
         * 参数1 表示当前消息的队列主题
         * 参数2表示消息的key
         * 参数3表示消息的value
         */

        for (int i = 0; i < 5; i++) {
            if(i%2==0){
                ProducerRecord<String, String> record=new ProducerRecord<String,String>("kafkastream-topic1","first"+i,"hello kafka");
                kafkaProducer.send(record);
            }else{
                ProducerRecord<String, String> record=new ProducerRecord<String,String>("kafkastream-topic1","first"+i,"hello itcast");
                kafkaProducer.send(record);
            }

        }


        /**
         * 同步发送
         */
//        Future<RecordMetadata> future = kafkaProducer.send(record);
//        RecordMetadata metadata = future.get();
//        System.out.println(metadata.offset());
        /**
         * 异步发送
         */
//        kafkaProducer.send(record, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata metadata, Exception exception) {
//                //表示有异常
//                if(exception!=null){
//                    //继续重试发送或者给抱一个错误
//                    throw new RuntimeException(exception);
//                }
//                //没有异常
//                System.out.println(metadata.offset());
//            }
//        });

        //4.关闭流
        kafkaProducer.close();
    }

}